// @ts-nocheck
/**
 * @Date: 2022-04-21 11:05:21
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-07-15 20:52:04
 * @FilePath: \weibo-api\controller\likeCtl.js
 * @Description: 点赞
 */
const { Like, User } = require("../model/index");
const { SuccessModel } = require("../ResModel");
//点赞博客
const likeBlog = async (ctx, next) => {
  const { id: userId } = ctx.session.userInfo;
  const { blogId } = ctx.params;
  const newData = { blogId, userId, like_status: true };
  try {
    let res = await Like.create(newData);
    ctx.body = new SuccessModel();
  } catch (error) {
    console.error("失败了", error);
  }
};
//取消点赞
const unLikeBlog = async (ctx, next) => {
  const { id: userId } = ctx.session.userInfo;
  const { blogId } = ctx.params;
  const newData = { like_status: false };
  try {
    let res = await Like.update(newData, {
      where: { blogId, userId },
    });
    if (res[0] > 0) {
      ctx.body = new SuccessModel();
    }
  } catch (error) {
    console.error(error);
    ctx.throw("更新失败", error);
  }
};
//获取点赞数量
const getBlogLikeCount = async (ctx, next) => {
  const { blogId } = ctx.params;
  let res = await Like.findAndCountAll({
    where: { blogId, like_status: true },
    attributes: ["id", "userId", "blogId", "createdAt"],
    include: [
      { model: User, attributes: ["id", "userName", "nickName", "avatar"] },
    ],
  });
  const likeList = res.rows.map((row) => row.dataValues);
  ctx.body = new SuccessModel({ count: res.count, likeList });
};
module.exports = { likeBlog, unLikeBlog, getBlogLikeCount };
